import pandas as pd
import numpy as np
from datetime import datetime


def main():
    df = pd.read_csv('anomaly_detection/data/ad_plan_data.csv')
    df = df.sort_values(by=['admc','aid'])
    df.dropna(inplace=True)
    df['dt'] = pd.to_datetime(df['dt'], format='%Y%m%d')

    cnt = 0
    filter_data = pd.DataFrame()
    admcs = df['admc'].unique()
    aids = df['aid'].unique()

    for i in range(1, 8):
        df[f'd{i}_rcost'] = 0
        df[f'd{i}_dnd'] = 0
        df[f'money1_{i}'] = 0
        df[f'dur1_{i}'] = 0

    for admc in admcs:
        for aid in aids:
            subset = df[(df['admc'] == admc) & (df['aid'] == aid)]

            missing_dates = pd.date_range(subset['dt'].min(), subset['dt'].max())
            existing_dates = subset['dt']
            missing_date = missing_dates.difference(existing_dates)
            
            if not missing_date.empty:

                cols_to_fill_zero = subset.columns[(df.columns != 'dt')&(df.columns != 'admc')&(df.columns != 'aid')]
                
                new_row = pd.DataFrame({
                    'dt':  missing_date,

                })
                new_row['aid'] = aid
                new_row['admc'] = admc
                new_row[cols_to_fill_zero] = 0

                df = pd.concat([df, new_row]).sort_values('dt').reset_index(drop=True)
                subset = pd.concat([subset, new_row]).sort_values('dt').reset_index(drop=True)
                subset['days'] = subset.index+1

                for idx, row in subset.iterrows():
                    days = row['days']
                    
                    for i in range(1, min(days+1, 8)):  
                        subset.loc[idx, f'd{i}_rcost'] =  subset.loc[idx - i + 1, 'rcost']
                        subset.loc[idx, f'd{i}_dnd'] = subset.loc[idx - i + 1, 'dnd']
                    for i in range(1,8):
                        subset[f'money1_{i}'] = subset[f'money_{i}'].shift(i-1).fillna(0).rolling(window=7,min_periods=0).sum()
                        subset[f'dur1_{i}'] = subset[f'dur_{i}'].shift(i-1).rolling(window=7,min_periods=0).sum()
            cnt += 1
            print(f'{cnt}/{len(admcs)*len(aids)}')
            if(cnt == 1) :
                filter_data = subset
            else :
                filter_data = pd.concat([filter_data,subset]).reset_index(drop=True)
        
    filter_data.to_csv(f'anomaly_detection/data/plan_data1.csv', index=False)

if __name__ == '__main__':
    main()